package com.yjd.merchant.api.interceptor;

import com.yjd.comm.vo.CachedKeys;
import com.yjd.merchant.api.util.AccessTokenUtil;
import com.yjd.comm.base.interceptor.BaseInterceptor;
import com.yjd.comm.base.model.ResultModel;
import com.yjd.comm.enums.ApiRequestWayEnum;
import com.yjd.comm.merchant.service.IMerchantService;
import com.yjd.comm.user.dto.MerchantSession;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.ServletUtil;
import com.yjd.comm.util.StringUtil;
import com.yjd.comm.vo.Constant.ResultEnum;
import org.apache.log4j.Logger;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class LoginInterceptor extends BaseInterceptor {

	private static Logger logger = Logger.getLogger(LoginInterceptor.class);
	public static final String URL_FILE = "nologinurl.txt";

	public boolean doPreHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		MerchantSession merchantSession = this.getSession(request, response); // 用户信息
		request.setAttribute(CachedKeys.MERCHANT_USER, merchantSession);

		// 判断有没有在拦截排除列表中
		if (!urlIsNeedValidate(ServletUtil.getRquestUriNotContainContextPath(request))) {
			return true;
		}

		if (merchantSession == null) {
			ServletUtil.outputJsonMessage(response, new ResultModel(ResultEnum.NOLOGIN, null, "请先登录", null).toMap());
			return false;
		}
		return true;
	}

	/**
	 * 获取登陆商户信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	private MerchantSession getSession(HttpServletRequest request, HttpServletResponse response) throws Exception {
		MerchantSession session = null;
		//用户id
		String user_id_str = request.getParameter("org_id");
		//请求令牌
		String access_token = request.getParameter("access_token");
		if(StringUtil.isEmpty(access_token)){
			access_token = request.getParameter("token");
		}
		//请求方式(1:普通的，其他值:手机端)
		String api_request_way = request.getParameter("api_request_way");
		if (StringUtil.isNotEmpty(user_id_str) && StringUtil.isNotEmpty(access_token)) {
			try {
				ApiRequestWayEnum apw = null;
				if(StringUtil.isNotEmpty(api_request_way) && ApiRequestWayEnum.WEB.getValue().toString().equals(api_request_way.trim())){
					apw = ApiRequestWayEnum.WEB;
					session = this.merchantService.getMerchantSession(Long.valueOf(user_id_str));
				}else{
					apw = ApiRequestWayEnum.APP;
					session = this.merchantService.getMerchantMobileSession(Long.valueOf(user_id_str));
				}
				if (session != null) {
					if (AccessTokenUtil.validToken(session, access_token, apw)) {
						return session;
					}

					session = null;
				}
			} catch (Exception e) {
				logger.error("获取用户信息有误:" + e.getMessage() + "," + FrameUtil.json(FrameUtil.newHashMap("user_id", user_id_str, "access_token", access_token)));
			}
		}
		return session;
	}

	@Resource
	private IMerchantService merchantService;

	@Override
	protected List<String> getUrlFiles() {
		return FrameUtil.newArrayList(LoginInterceptor.URL_FILE);
	}

}
